import url from './url.js'
import {lkRequest}from  './lkRequest'
const app = getApp();
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
        n = n.toString()
        return n[1] ? n : '0' + n
    }
    // 根据分数获取颜色
function getColorWith(scores) {
    // 阴证总分
    var yinzScore = 0;
    // 阳证总分
    var yangzScore = 0;
    // 是否规则2
    var isTwo = true;

    for (let i = 0; i < scores.length; i++) {
        let score = scores[i];
        if (i < 3) {
            yinzScore += score;
        } else {
            yangzScore += score;
        }
        if (score > 15) {
            isTwo = false;
        }
    }
    // console.log(scores);
    if (isTwo) {
        //深绿-浅绿
        return getColorWithB((yinzScore + yangzScore) / 90, 1);
    } else {
        // 规则1
        // （阳证总分-阴证总分）/3
        var chaScore = (yangzScore - yinzScore) / 3;
        if (chaScore === 0) {
            // 0分橙色
            return "#FF6600"
        } else if (chaScore > 0) {
            // 1-100分 浅红-深红
            return getColorWithB(chaScore / 100, 0);
        } else {
            // -100--1分 深蓝-浅蓝
            return getColorWithB((100 + chaScore) / 100, 2);
        }
    }
}

function getColorWithB(bl, colorType) {
    if (colorType === 0) {
        //红
        let redColor = getShortColor("fd9f9f", "ff0000", bl);
        console.log("redColor = " + redColor);
        return redColor;
    } else if (colorType === 1) {
        //绿
        let greenColor = getShortColor("04bd04", "95f795", bl);
        console.log("greenColor = " + greenColor);
        return greenColor;
    } else if (colorType === 2) {
        //蓝
        let blueColor = getShortColor("0000ff", "9e9ffc", bl);
        console.log("blueColor = " + blueColor);
        return blueColor;
    }
}
// 获取颜色
function getShortColor(startColor, endColor, bl) {
    var redResult = get16ResultFrom(startColor.substring(0, 2), endColor.substring(0, 2), bl);
    var greenResult = get16ResultFrom(startColor.substring(2, 4), endColor.substring(2, 4), bl);
    var blueResult = get16ResultFrom(startColor.substring(4, 6), endColor.substring(4, 6), bl);

    return "#" + redResult + greenResult + blueResult
}
// 根据起始及结束16进制加上比例计算结果
function get16ResultFrom(startStr, endStr, bl) {
    var start = parseInt("0x" + startStr);
    var end = parseInt("0x" + endStr);

    var section = bl * (start - end)

    var result = (start - section).toString(16).substring(0, 2)

    if (result.indexOf(".") !== -1) {
        result = result.replace(".", "");
        result = "0" + result
    }

    if (result.length === 0) {
        result = "00"
    } else if (result.length === 1) {
        result = "0" + result
    }

    return result
}

const uuid = () => {
    const time = new Date().getTime();
    var timeLen = time.toString(16).length;
    var nextCode = ''
    for (var i = 0; i < (32 - timeLen); i++) {
        nextCode += parseInt(Math.random() * 15).toString(16);
    }
    var uuid = time.toString(16) + nextCode;
    console.log(uuid + '---' + uuid.length);
    return uuid;
}

// m-n 随机数
let rand = (m,n) => {
    m = m || 1;
    n = n || 5;
    return m + parseInt(Math.random()*(n-m))
}

/**
 * 数组元素交换位置
 * @param {array} arr 数组
 * @param {number} index1 添加项目的位置
 * @param {number} index2 删除项目的位置
 * index1和index2分别是两个数组的索引值，即是两个要交换元素位置的索引值，如1，5就是数组中下标为1和5的两个元素交换位置
 */
const swapArray = (arr, index1, index2) => {
    var itemArr = [arr[0], arr[1], arr[2]];
    arr[index1] = itemArr[index2];
    arr[index2] = itemArr[index1];
    return arr;
}
/**
 * [decodeUrlParam 解码参数]
 * @param  {[type]} paramObj [参数对象]
 * @return {[type]}          [description]
 */
function decodeUrlParam(paramObj = {}) {
    if (paramObj && typeof paramObj === 'object') {
        let keys = Object.keys(paramObj);
        for (let key of keys) {
            let val = paramObj[key];
            if (val) {
                let strVal = decodeURIComponent(val);
                try {
                    paramObj[key] = JSON.parse(strVal);
                } catch (ex) {
                    paramObj[key] = strVal;
                }
            }
        }
    }
    return paramObj;
}
export function promisify(fn) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function (res) {
                resolve(res)
            }
            obj.fail = function (res) {
                reject(res)
            }
            fn(obj)
        })
    }
}
/**
 * 动态生成二维码
 * @param scene 参数
 *        page  路径 pages/index/main
 *        width 宽 148
 *        auto_color  false
 *        line_color  {"r":0,"g":0,"b":0},"is_hyaline":true}
 * }
 */
function getQRCode(options, callback) {
    lkRequest({
        url: url.urls.getQRCode,
        method: 'POST',
        params: options || null,
        contentType: 'application/json;charset=utf-8'
    },(res)=>{
        console.log(res)
        callback(res)
    },(err)=>{
        wx.showToast({
            title: err.data.message,
            icon: 'none',
            duration: 3000
        })
    })
    // wx.request({
    //     method: 'POST',
    //     url: url.urls.getQRCode,
    //     header: {
    //         'Content-Type': 'application/json;charset=utf-8'
    //     },
    //     data: options || null,
    //     success: function (res) {
    //         console.log(res)
    //         callback(res)
    //     },
    //     fail: function(res) {
    //         wx.showToast({
    //             title: res.data.message,
    //             icon: 'none',
    //             duration: 3000
    //         })
    //     }
    // })
}
module.exports = {
    formatTime: formatTime,
    uuid: uuid,
    // formatTime: formatTime,
    getColorWith: getColorWith,
    getColorWithB: getColorWithB,
    swapArray: swapArray,
    rand: rand,
    getQRCode: getQRCode,
    promisify: promisify,
    decodeUrlParam
}
